import {
  ElementRef,
  EventEmitter,
  Injector,
  Input,
  Output,
  Component
} from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import * as XLSX from 'ts-xlsx';

@Component({
  selector: 'excel-import',
  template: `
    <span class="input-group-btn" style="display:block;width:100%;">
      <span
        class="btn btn-file btn-{{btnColor}}"
        [ngClass]="{ 'only-link': onlyLink }"
      >
        <i *ngIf="showIcon" class="fa fa-plus"></i> {{ btnText
        }}<input
          type="file"
          name="file"
          single
          (change)="excelInputUpload($event)"
        />
      </span>
      <label class="label-file"></label>
    </span>
  `,
  styles: [
    `
      .only-link {
        color: #575962 !important;
        background-color: #fff !important;
        border-color: #fff !important;
      }
    `,
    `
      .only-link:hover:not(:disabled) {
        color: #575962 !important;
        background: #f4f5f8 !important;
        text-decoration: none !important;
      }
    `,
    `
      .btn-file {
        position: relative;
        overflow: hidden;
        width:100%;
        text-align:left;
      }
    `,
    `
      .btn-file input[type="file"] {
        position: absolute;
        top: 0;
        right: 0;
        min-width: 100%;
        min-height: 100%;
        font-size: 100px;
        text-align: right;
        filter: alpha(opacity=0);
        opacity: 0;
        background: red;
        cursor: inherit;
        display: block;
      }
    `,
    `
      .label-file {
        font-size: 18px;
        color: #999;
      }
    `
  ]
})
export class ExcelImportComponent extends AppComponentBase {
  @Input() btnColor = '';
  @Input() btnText = '选择文件';
  @Input() showIcon = true;
  @Input() onlyLink = false;

  @Output() onUpload = new EventEmitter<Array<any>>();

  fileName = '';

  constructor(injector: Injector, private _element: ElementRef) {
    super(injector);
  }

  excelInputUpload(event) {
    let wb: XLSX.IWorkBook; //读取完成的数据
    let rABS = false; //是否将文件读取为二进制字符串

    if (!(event.target.files && event.target.files[0])) {
      return;
    }

    let f = event.target.files[0];

    this.fileName = f.name;

    const reader = new FileReader();

    reader.onload = e => {
      let data = reader.result;
      if (rABS) {
        wb = XLSX.read(btoa(this.fixdata(data)), {
          //手动转化
          type: 'base64'
        });
      } else {
        wb = XLSX.read(data, {
          type: 'binary'
        });
      }

      let datas = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);

      let str = JSON.stringify(datas);

      let jsonArr = JSON.parse(str) as Array<any>; //转化为JSONArray对象
      this.onUpload.emit(jsonArr);
    };

    if (rABS) {
      reader.readAsArrayBuffer(f);
    } else {
      reader.readAsBinaryString(f);
    }
    let files= document.getElementsByName("file")[0] as HTMLInputElement;
    files.value="";

  }

  fixdata(data) {
    //文件流转BinaryString
    let o = '',
      l = 0,
      w = 10240;
    for (; l < data.byteLength / w; ++l) {
      o += String.fromCharCode.apply(
        null,
        new Uint8Array(data.slice(l * w, l * w + w))
      );
    }
    o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
    return o;
  }
}
